<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>天工开悟-农业AI对话助手</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .app-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 1200px;
            height: 600px;
            display: flex;
            overflow: hidden;
        }

        .sidebar {
            width: 300px;
            background: #f8f9fa;
            border-right: 1px solid #e0e0e0;
            display: flex;
            flex-direction: column;
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid #e0e0e0;
            background: white;
        }

        .new-chat-btn {
            width: 100%;
            padding: 12px 16px;
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .new-chat-btn:hover {
            background: #45a049;
        }

        .chat-history {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }

        .chat-item {
            padding: 12px 16px;
            margin-bottom: 8px;
            border-radius: 10px;
            cursor: pointer;
            transition: background-color 0.3s;
            border: 1px solid transparent;
            position: relative;
        }

        .chat-item:hover {
            background: #e3f2fd;
        }

        .chat-item.active {
            background: #e8f5e8;
            border-color: #4CAF50;
        }

        .chat-item-title {
            font-weight: 500;
            font-size: 14px;
            color: #333;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .chat-item-preview {
            font-size: 12px;
            color: #666;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .chat-item-time {
            font-size: 11px;
            color: #999;
            margin-top: 4px;
        }

        .chat-item-actions {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            display: none;
            gap: 4px;
        }

        .chat-item:hover .chat-item-actions {
            display: flex;
        }

        .chat-item-action {
            background: none;
            border: none;
            cursor: pointer;
            padding: 4px;
            border-radius: 4px;
            font-size: 12px;
            color: #666;
            transition: all 0.3s;
        }

        .chat-item-action:hover {
            background: #ddd;
            color: #333;
        }

        .chat-item-action.delete:hover {
            background: #ffebee;
            color: #c62828;
        }

        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat-header {
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            color: white;
            padding: 20px;
            text-align: center;
            position: relative;
        }

        .chat-header h1 {
            font-size: 24px;
            margin-bottom: 5px;
        }

        .chat-header p {
            font-size: 14px;
            opacity: 0.9;
        }

        .header-controls {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .model-selector select, .stream-toggle {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 8px 12px;
            border-radius: 8px;
            font-size: 14px;
        }

        .model-selector select option {
            background: #4CAF50;
            color: white;
        }

        .stream-toggle {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .stream-toggle:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        .stream-toggle input[type="checkbox"] {
            margin: 0;
        }

        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f8f9fa;
        }

        .message {
            margin-bottom: 20px;
            display: flex;
            align-items: flex-start;
        }

        .message.user {
            justify-content: flex-end;
        }

        .message.assistant {
            justify-content: flex-start;
        }

        .message-content {
            max-width: 70%;
            padding: 15px 20px;
            border-radius: 18px;
            word-wrap: break-word;
            line-height: 1.5;
        }

        .message.user .message-content {
            background: #007bff;
            color: white;
            border-bottom-right-radius: 5px;
        }

        .message.assistant .message-content {
            background: white;
            color: #333;
            border: 1px solid #e0e0e0;
            border-bottom-left-radius: 5px;
        }

        .message.streaming .message-content {
            position: relative;
        }

        .message.streaming .message-content::after {
            content: '▋';
            color: #4CAF50;
            animation: blink 1s infinite;
            margin-left: 2px;
        }

        @keyframes blink {
            0%, 50% { opacity: 1; }
            51%, 100% { opacity: 0; }
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin: 0 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: white;
            font-size: 14px;
        }

        .message.user .message-avatar {
            background: #007bff;
            order: 1;
        }

        .message.assistant .message-avatar {
            background: #4CAF50;
        }

        .chat-input-container {
            padding: 20px;
            background: white;
            border-top: 1px solid #e0e0e0;
        }

        .input-group {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }

        .input-wrapper {
            flex: 1;
            position: relative;
        }

        .chat-input {
            width: 100%;
            min-height: 50px;
            max-height: 120px;
            padding: 15px 50px 15px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 25px;
            font-size: 16px;
            resize: none;
            outline: none;
            transition: border-color 0.3s;
        }

        .chat-input:focus {
            border-color: #4CAF50;
        }

        .image-upload-btn {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            cursor: pointer;
            font-size: 20px;
            color: #666;
            transition: color 0.3s;
        }

        .image-upload-btn:hover {
            color: #4CAF50;
        }

        .send-btn {
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            cursor: pointer;
            font-size: 20px;
            transition: background-color 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .send-btn:hover {
            background: #45a049;
        }

        .send-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .image-preview {
            margin-top: 10px;
            display: none;
        }

        .image-preview img {
            max-width: 200px;
            max-height: 150px;
            border-radius: 10px;
            border: 2px solid #e0e0e0;
        }

        .remove-image {
            background: #ff4444;
            color: white;
            border: none;
            border-radius: 50%;
            width: 25px;
            height: 25px;
            cursor: pointer;
            margin-left: 10px;
            font-size: 12px;
        }

        .typing-indicator {
            display: none;
            align-items: center;
            margin-bottom: 20px;
        }

        .typing-dots {
            display: flex;
            gap: 4px;
            margin-left: 50px;
        }

        .typing-dots span {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #4CAF50;
            animation: typing 1.4s infinite ease-in-out;
        }

        .typing-dots span:nth-child(1) { animation-delay: -0.32s; }
        .typing-dots span:nth-child(2) { animation-delay: -0.16s; }

        @keyframes typing {
            0%, 80%, 100% { transform: scale(0); }
            40% { transform: scale(1); }
        }

        .error-message {
            background: #ffebee;
            color: #c62828;
            padding: 10px 15px;
            border-radius: 10px;
            margin-bottom: 10px;
            border-left: 4px solid #c62828;
        }

        .api-key-input {
            margin-bottom: 15px;
        }

        .api-key-input input {
            width: 100%;
            padding: 10px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 14px;
            outline: none;
        }

        .api-key-input input:focus {
            border-color: #4CAF50;
        }

        .hidden {
            display: none !important;
        }

        .sidebar-toggle {
            display: none;
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1000;
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            font-size: 18px;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        @media (max-width: 768px) {
            .app-container {
                height: 100vh;
                border-radius: 0;
                max-width: 100%;
                position: relative;
            }

            .sidebar {
                position: absolute;
                left: -300px;
                top: 0;
                height: 100%;
                z-index: 999;
                transition: left 0.3s ease;
                box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
            }

            .sidebar.open {
                left: 0;
            }

            .sidebar-toggle {
                display: block;
            }

            .message-content {
                max-width: 85%;
            }

            .header-controls {
                position: static;
                transform: none;
                margin-top: 10px;
                align-items: center;
            }

            .chat-header {
                text-align: left;
            }
        }
    </style>
</head>
<body>
    <button class="sidebar-toggle" id="sidebarToggle">☰</button>

    <div class="app-container">
        <div class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <button class="new-chat-btn" id="newChatBtn">
                    ➕ 新建对话
                </button>
            </div>
            <div class="chat-history" id="chatHistory">
                <!-- 历史对话列表将在这里动态生成 -->
            </div>
        </div>

        <div class="chat-container">
            <div class="chat-header">
                <h1>🌾 天工开悟农业AI助手</h1>
                <p>专业的农业多模态大模型，助力智慧农业发展</p>
                <div class="header-controls">
                    <div class="model-selector">
                        <select id="modelSelect">
                            <option value="KwooVa">KwooVa (多模态)</option>
                            <option value="KwooLa">KwooLa (问答)</option>
                        </select>
                    </div>
                    <label class="stream-toggle">
                        <input type="checkbox" id="streamToggle" checked>
                        <span>流式输出</span>
                    </label>
                </div>
            </div>

        <div class="chat-messages" id="chatMessages">
            <div class="api-key-input">
                <input type="password" id="apiKeyInput" value="sk-jZFoeRA0If26Dl91tfVGPrxrgwylG9w5QVWUzVIqr5SZuQ8W" placeholder="请输入您的API密钥 (sk-xxxx)" />
            </div>
            <div class="message assistant">
                <div class="message-avatar">🤖</div>
                <div class="message-content">
                    您好！我是天工开悟农业AI助手。我可以帮助您：<br>
                    • 识别作物病虫害<br>
                    • 提供防治建议<br>
                    • 解答农业相关问题<br>
                    • 分析农作物图片<br><br>
                    请先输入您的API密钥，然后开始对话吧！
                </div>
            </div>
            <div class="typing-indicator" id="typingIndicator">
                <div class="typing-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
            </div>
        </div>

        <div class="chat-input-container">
            <div class="input-group">
                <div class="input-wrapper">
                    <textarea
                        id="chatInput"
                        class="chat-input"
                        placeholder="输入您的问题，或上传作物图片进行诊断..."
                        rows="1"
                    ></textarea>
                    <button class="image-upload-btn" id="imageUploadBtn" title="上传图片">📷</button>
                    <input type="file" id="imageInput" accept="image/*" style="display: none;">
                </div>
                <button class="send-btn" id="sendBtn" title="发送">➤</button>
            </div>
            <div class="image-preview" id="imagePreview">
                <img id="previewImg" src="" alt="预览图片">
                <button class="remove-image" id="removeImage" title="移除图片">×</button>
            </div>
        </div>
    </div>

    <script>
        class AgricultureChatBot {
            constructor() {
                this.apiKey = '';
                this.selectedModel = 'KwooVa';
                this.streamEnabled = true;
                this.messages = [];
                this.currentImage = null;
                this.isLoading = false;
                this.chatSessions = [];
                this.currentSessionId = null;
                this.currentStreamingMessage = null;

                this.initializeElements();
                this.bindEvents();
                this.loadApiKey();
                this.loadChatSessions();
                this.createNewChat();
            }

            initializeElements() {
                this.chatMessages = document.getElementById('chatMessages');
                this.chatInput = document.getElementById('chatInput');
                this.sendBtn = document.getElementById('sendBtn');
                this.imageUploadBtn = document.getElementById('imageUploadBtn');
                this.imageInput = document.getElementById('imageInput');
                this.imagePreview = document.getElementById('imagePreview');
                this.previewImg = document.getElementById('previewImg');
                this.removeImageBtn = document.getElementById('removeImage');
                this.typingIndicator = document.getElementById('typingIndicator');
                this.modelSelect = document.getElementById('modelSelect');
                this.apiKeyInput = document.getElementById('apiKeyInput');
                this.sidebar = document.getElementById('sidebar');
                this.sidebarToggle = document.getElementById('sidebarToggle');
                this.newChatBtn = document.getElementById('newChatBtn');
                this.chatHistory = document.getElementById('chatHistory');
                this.streamToggle = document.getElementById('streamToggle');
            }

            bindEvents() {
                this.sendBtn.addEventListener('click', () => this.sendMessage());
                this.chatInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        this.sendMessage();
                    }
                });

                this.imageUploadBtn.addEventListener('click', () => {
                    this.imageInput.click();
                });

                this.imageInput.addEventListener('change', (e) => {
                    this.handleImageUpload(e);
                });

                this.removeImageBtn.addEventListener('click', () => {
                    this.removeImage();
                });

                this.modelSelect.addEventListener('change', (e) => {
                    this.selectedModel = e.target.value;
                    this.updateImageUploadVisibility();
                });

                this.apiKeyInput.addEventListener('input', (e) => {
                    this.apiKey = e.target.value.trim();
                    this.saveApiKey();
                });

                this.sidebarToggle.addEventListener('click', () => {
                    this.toggleSidebar();
                });

                this.newChatBtn.addEventListener('click', () => {
                    this.createNewChat();
                });

                this.streamToggle.addEventListener('change', (e) => {
                    this.streamEnabled = e.target.checked;
                });

                // 自动调整输入框高度
                this.chatInput.addEventListener('input', () => {
                    this.chatInput.style.height = 'auto';
                    this.chatInput.style.height = Math.min(this.chatInput.scrollHeight, 120) + 'px';
                });

                // 点击空白区域关闭侧边栏（移动端）
                document.addEventListener('click', (e) => {
                    if (window.innerWidth <= 768 &&
                        !this.sidebar.contains(e.target) &&
                        !this.sidebarToggle.contains(e.target) &&
                        this.sidebar.classList.contains('open')) {
                        this.toggleSidebar();
                    }
                });
            }

            loadApiKey() {
                const savedApiKey = localStorage.getItem('kwoovaApiKey');
                if (savedApiKey) {
                    this.apiKey = savedApiKey;
                    this.apiKeyInput.value = savedApiKey;
                } else {
                    // 如果没有保存的API key，使用HTML中的默认值
                    this.apiKey = this.apiKeyInput.value.trim();
                }
            }

            saveApiKey() {
                if (this.apiKey) {
                    localStorage.setItem('kwoovaApiKey', this.apiKey);
                }
            }

            updateImageUploadVisibility() {
                // KwooVa支持图片上传，KwooLa不支持
                const isMultimodal = this.selectedModel === 'KwooVa';
                this.imageUploadBtn.style.display = isMultimodal ? 'block' : 'none';

                if (!isMultimodal && this.currentImage) {
                    this.removeImage();
                }
            }

            async handleImageUpload(event) {
                const file = event.target.files[0];
                if (!file) return;

                // 检查文件类型
                const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/bmp', 'image/webp'];
                if (!allowedTypes.includes(file.type)) {
                    this.showError('请上传支持的图片格式：JPG, PNG, BMP, WebP');
                    return;
                }

                // 检查文件大小 (10MB)
                if (file.size > 10 * 1024 * 1024) {
                    this.showError('图片大小不能超过10MB');
                    return;
                }

                // 显示上传中状态
                this.imageUploadBtn.disabled = true;
                this.imageUploadBtn.textContent = '⏳';
                this.imageUploadBtn.title = '上传中...';

                try {
                    // 使用API上传图片
                    const imageUrl = await this.uploadImageToAPI(file);

                    // 上传成功，设置预览
                    this.currentImage = imageUrl;
                    this.previewImg.src = imageUrl;
                    this.imagePreview.style.display = 'block';

                } catch (error) {
                    this.showError('图片上传失败：' + error.message);
                } finally {
                    // 恢复按钮状态
                    this.imageUploadBtn.disabled = false;
                    this.imageUploadBtn.textContent = '📷';
                    this.imageUploadBtn.title = '上传图片';
                }
            }

            async uploadImageToAPI(file) {
                if (!this.apiKey) {
                    throw new Error('请先输入API密钥');
                }

                const formData = new FormData();
                formData.append('type', 'image');
                formData.append('file', file);

                const response = await fetch('https://api.tgkwai.com/api/v1/attachments/upload', {
                    method: 'POST',
                    headers: {
                        'X-Token': `Bearer ${this.apiKey}`
                    },
                    body: formData
                });

                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new Error(errorData.msg || `HTTP ${response.status}: ${response.statusText}`);
                }

                const data = await response.json();
                if (data.code !== 200) {
                    throw new Error(data.msg || '上传失败');
                }

                // 返回完整的图片URL
                return `https://static.tgkwai.com/uploads/${data.data}`;
            }

            removeImage() {
                this.currentImage = null;
                this.imagePreview.style.display = 'none';
                this.imageInput.value = '';
            }

            async sendMessage() {
                if (!this.apiKey) {
                    this.showError('请先输入API密钥');
                    return;
                }

                const message = this.chatInput.value.trim();
                if (!message && !this.currentImage) {
                    return;
                }

                if (this.isLoading) {
                    return;
                }

                this.isLoading = true;
                this.sendBtn.disabled = true;

                // 添加用户消息
                this.addMessage('user', message, this.currentImage);

                // 清空输入
                this.chatInput.value = '';
                this.chatInput.style.height = 'auto';

                // 显示加载指示器
                this.showTypingIndicator();

                try {
                    if (this.streamEnabled) {
                        // 流式输出模式
                        this.hideTypingIndicator();
                        console.log('请求参数：')
                        console.log(message)
                        console.log(this.currentImage)
                        const response = await this.callAPI(message, this.currentImage);
                        // 流式消息已经在processStreamResponse中处理，这里只需要保存到历史
                        if (response) {
                            const messageData = { role: 'assistant', content: response, timestamp: new Date().toISOString() };
                            this.messages.push(messageData);
                            this.updateCurrentSessionLastMessage();
                        }
                    } else {
                        // 普通模式
                        const response = await this.callAPI(message, this.currentImage);
                        this.hideTypingIndicator();
                        this.addMessage('assistant', response);
                    }
                } catch (error) {
                    this.hideTypingIndicator();
                    this.removeStreamingMessage(); // 清理可能存在的流式消息
                    this.showError('发送失败：' + error.message);
                } finally {
                    this.isLoading = false;
                    this.sendBtn.disabled = false;
                    this.removeImage();
                }
            }

            async callAPI(message, image) {
                const url = 'https://api.tgkwai.com/api/v1/qamodel/chat/completions';

                // 构建当前消息
                let currentMessage;
                if (image && this.selectedModel === 'KwooVa') {
                    // 多模态消息格式 - 现在image是URL而不是base64
                    currentMessage = {
                        role: "user",
                        content: [
                            {
                                type: "text",
                                text: message
                            },
                            {
                                type: "image_url",
                                image_url: {
                                    url: image
                                }
                            }
                        ]
                    };
                } else {
                    // 纯文本消息格式
                    currentMessage = {
                        role: "user",
                        content: message
                    };
                }

                // 构建完整的消息历史（多轮对话支持）
                const conversationMessages = [];

                // 添加历史消息（不包括当前正在发送的消息，因为它已经在sendMessage中被添加到this.messages了）
                // 我们需要排除最后一条用户消息，因为那是当前正在发送的消息
                const historyMessages = this.messages.slice(0, -1); // 排除最后一条消息

                historyMessages.forEach(msg => {
                    if (msg.role === 'user') {
                        if (msg.image && this.selectedModel === 'KwooVa') {
                            conversationMessages.push({
                                role: "user",
                                content: [
                                    {
                                        type: "text",
                                        text: typeof msg.content === 'string' ? msg.content : '图片消息'
                                    },
                                    {
                                        type: "image_url",
                                        image_url: {
                                            url: msg.image  // 现在存储的是URL
                                        }
                                    }
                                ]
                            });
                        } else {
                            conversationMessages.push({
                                role: "user",
                                content: typeof msg.content === 'string' ? msg.content : '图片消息'
                            });
                        }
                    } else if (msg.role === 'assistant') {
                        conversationMessages.push({
                            role: "assistant",
                            content: msg.content
                        });
                    }
                });

                // 添加当前消息
                conversationMessages.push(currentMessage);

                const requestBody = {
                    model: this.selectedModel,
                    messages: conversationMessages,
                    stream: this.streamEnabled,
                    temperature: 0.7,
                    max_tokens: 4096
                };
                console.log('发送的信息参数2：');
                console.log(requestBody);
                if (this.streamEnabled) {
                    return await this.handleStreamResponse(url, requestBody);
                } else {
                    return await this.handleNormalResponse(url, requestBody);
                }
            }

            async handleNormalResponse(url, requestBody) {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${this.apiKey}`
                    },
                    body: JSON.stringify(requestBody)
                });

                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new Error(errorData.error?.message || `HTTP ${response.status}: ${response.statusText}`);
                }

                const data = await response.json();
                return data.choices[0].message.content;
            }

            async handleStreamResponse(url, requestBody) {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${this.apiKey}`
                    },
                    body: JSON.stringify(requestBody)
                });

                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new Error(errorData.error?.message || `HTTP ${response.status}: ${response.statusText}`);
                }

                return await this.processStreamResponse(response);
            }

            async processStreamResponse(response) {
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let fullContent = '';

                // 创建流式消息容器
                this.currentStreamingMessage = this.createStreamingMessage();

                try {
                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;

                        const chunk = decoder.decode(value);
                        const lines = chunk.split('\n');

                        for (const line of lines) {
                            if (line.startsWith('data: ')) {
                                const data = line.slice(6);
                                if (data === '[DONE]') {
                                    this.finalizeStreamingMessage();
                                    return fullContent;
                                }

                                try {
                                    const parsed = JSON.parse(data);
                                    const content = parsed.choices?.[0]?.delta?.content;
                                    if (content) {
                                        fullContent += content;
                                        this.updateStreamingMessage(fullContent);
                                    }
                                } catch (e) {
                                    // 忽略解析错误
                                }
                            }
                        }
                    }
                } catch (error) {
                    this.removeStreamingMessage();
                    throw error;
                }

                this.finalizeStreamingMessage();
                return fullContent;
            }

            createStreamingMessage() {
                const messageDiv = document.createElement('div');
                messageDiv.className = 'message assistant streaming';
                messageDiv.id = 'streaming-message';

                const avatar = document.createElement('div');
                avatar.className = 'message-avatar';
                avatar.textContent = '🤖';

                const messageContent = document.createElement('div');
                messageContent.className = 'message-content';
                messageContent.id = 'streaming-content';

                messageDiv.appendChild(avatar);
                messageDiv.appendChild(messageContent);

                // 在输入框之前插入消息
                this.chatMessages.insertBefore(messageDiv, this.typingIndicator);
                this.scrollToBottom();

                return messageDiv;
            }

            updateStreamingMessage(content) {
                const contentDiv = document.getElementById('streaming-content');
                if (contentDiv) {
                    contentDiv.innerHTML = this.formatMessage(content);
                    this.scrollToBottom();
                }
            }

            finalizeStreamingMessage() {
                const streamingDiv = document.getElementById('streaming-message');
                if (streamingDiv) {
                    streamingDiv.classList.remove('streaming');
                    streamingDiv.removeAttribute('id');
                }

                const contentDiv = document.getElementById('streaming-content');
                if (contentDiv) {
                    contentDiv.removeAttribute('id');
                }

                this.currentStreamingMessage = null;
            }

            removeStreamingMessage() {
                const streamingDiv = document.getElementById('streaming-message');
                if (streamingDiv) {
                    streamingDiv.remove();
                }
                this.currentStreamingMessage = null;
            }

            addMessage(role, content, image = null, saveToSession = true) {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${role}`;

                const avatar = document.createElement('div');
                avatar.className = 'message-avatar';
                avatar.textContent = role === 'user' ? '👤' : '🤖';

                const messageContent = document.createElement('div');
                messageContent.className = 'message-content';

                if (image && role === 'user') {
                    const img = document.createElement('img');
                    img.src = image;  // 现在image是URL而不是base64
                    img.style.maxWidth = '200px';
                    img.style.maxHeight = '150px';
                    img.style.borderRadius = '10px';
                    img.style.marginBottom = '10px';
                    img.style.display = 'block';
                    img.onerror = () => {
                        // 如果图片加载失败，显示错误信息
                        img.style.display = 'none';
                        const errorText = document.createElement('div');
                        errorText.textContent = '图片加载失败';
                        errorText.style.color = '#999';
                        errorText.style.fontSize = '12px';
                        errorText.style.marginBottom = '10px';
                        messageContent.appendChild(errorText);
                    };
                    messageContent.appendChild(img);
                }

                const textContent = document.createElement('div');
                textContent.innerHTML = this.formatMessage(content);
                messageContent.appendChild(textContent);

                messageDiv.appendChild(avatar);
                messageDiv.appendChild(messageContent);

                // 在输入框之前插入消息
                const inputContainer = document.querySelector('.api-key-input');
                this.chatMessages.insertBefore(messageDiv, this.typingIndicator);

                // 保存到当前会话
                if (saveToSession) {
                    const messageData = { role, content, image, timestamp: new Date().toISOString() };
                    this.messages.push(messageData);

                    // 如果是用户消息且是第一条消息，更新会话标题
                    if (role === 'user' && this.messages.filter(m => m.role === 'user').length === 1) {
                        const messageText = typeof content === 'string' ? content : '图片消息';
                        this.updateCurrentSessionTitle(messageText);
                    }

                    this.updateCurrentSessionLastMessage();
                }

                // 滚动到底部
                this.scrollToBottom();
            }

            formatMessage(content) {
                if (!content) return '';

                // 简单的格式化：换行和基本的markdown支持
                return content
                    .replace(/\n/g, '<br>')
                    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                    .replace(/\*(.*?)\*/g, '<em>$1</em>');
            }

            showTypingIndicator() {
                this.typingIndicator.style.display = 'flex';
                this.scrollToBottom();
            }

            hideTypingIndicator() {
                this.typingIndicator.style.display = 'none';
            }

            showError(message) {
                const errorDiv = document.createElement('div');
                errorDiv.className = 'error-message';
                errorDiv.textContent = message;

                this.chatMessages.insertBefore(errorDiv, this.typingIndicator);
                this.scrollToBottom();

                // 5秒后自动移除错误消息
                setTimeout(() => {
                    if (errorDiv.parentNode) {
                        errorDiv.parentNode.removeChild(errorDiv);
                    }
                }, 5000);
            }

            scrollToBottom() {
                setTimeout(() => {
                    this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
                }, 100);
            }

            // 侧边栏相关方法
            toggleSidebar() {
                this.sidebar.classList.toggle('open');
            }

            createNewChat() {
                const sessionId = this.generateSessionId();
                const newSession = {
                    id: sessionId,
                    title: '新对话',
                    messages: [],
                    createdAt: new Date().toISOString(),
                    lastMessageAt: new Date().toISOString()
                };

                this.chatSessions.unshift(newSession);
                this.currentSessionId = sessionId;
                this.messages = [];
                this.clearChatMessages();
                this.addWelcomeMessage();
                this.saveChatSessions();
                this.renderChatHistory();

                // 移动端自动关闭侧边栏
                if (window.innerWidth <= 768) {
                    this.sidebar.classList.remove('open');
                }
            }

            loadChatSession(sessionId) {
                const session = this.chatSessions.find(s => s.id === sessionId);
                if (!session) return;

                this.currentSessionId = sessionId;
                this.messages = [...session.messages];
                this.clearChatMessages();

                if (this.messages.length === 0) {
                    this.addWelcomeMessage();
                } else {
                    this.messages.forEach(msg => {
                        this.addMessage(msg.role, msg.content, msg.image, false);
                    });
                }

                this.renderChatHistory();

                // 移动端自动关闭侧边栏
                if (window.innerWidth <= 768) {
                    this.sidebar.classList.remove('open');
                }
            }

            deleteChatSession(sessionId) {
                if (confirm('确定要删除这个对话吗？')) {
                    this.chatSessions = this.chatSessions.filter(s => s.id !== sessionId);

                    if (this.currentSessionId === sessionId) {
                        if (this.chatSessions.length > 0) {
                            this.loadChatSession(this.chatSessions[0].id);
                        } else {
                            this.createNewChat();
                        }
                    }

                    this.saveChatSessions();
                    this.renderChatHistory();
                }
            }

            updateCurrentSessionTitle(message) {
                if (!this.currentSessionId) return;

                const session = this.chatSessions.find(s => s.id === this.currentSessionId);
                if (session && session.title === '新对话') {
                    // 使用用户第一条消息的前20个字符作为标题
                    session.title = message.length > 20 ? message.substring(0, 20) + '...' : message;
                    this.saveChatSessions();
                    this.renderChatHistory();
                }
            }

            updateCurrentSessionLastMessage() {
                if (!this.currentSessionId) return;

                const session = this.chatSessions.find(s => s.id === this.currentSessionId);
                if (session) {
                    session.lastMessageAt = new Date().toISOString();
                    session.messages = [...this.messages];
                    this.saveChatSessions();
                }
            }

            renderChatHistory() {
                this.chatHistory.innerHTML = '';

                this.chatSessions.forEach(session => {
                    const chatItem = document.createElement('div');
                    chatItem.className = `chat-item ${session.id === this.currentSessionId ? 'active' : ''}`;

                    const lastMessage = session.messages.length > 0 ?
                        session.messages[session.messages.length - 1].content : '暂无消息';
                    const preview = typeof lastMessage === 'string' ? lastMessage : '图片消息';

                    chatItem.innerHTML = `
                        <div class="chat-item-title">${session.title}</div>
                        <div class="chat-item-preview">${preview.length > 30 ? preview.substring(0, 30) + '...' : preview}</div>
                        <div class="chat-item-time">${this.formatTime(session.lastMessageAt)}</div>
                        <div class="chat-item-actions">
                            <button class="chat-item-action delete" onclick="chatBot.deleteChatSession('${session.id}')" title="删除">🗑️</button>
                        </div>
                    `;

                    chatItem.addEventListener('click', (e) => {
                        if (!e.target.classList.contains('chat-item-action')) {
                            this.loadChatSession(session.id);
                        }
                    });

                    this.chatHistory.appendChild(chatItem);
                });
            }

            clearChatMessages() {
                // 清空聊天消息，但保留API密钥输入框和欢迎消息
                const messages = this.chatMessages.querySelectorAll('.message:not(.welcome)');
                messages.forEach(msg => msg.remove());

                const errors = this.chatMessages.querySelectorAll('.error-message');
                errors.forEach(error => error.remove());
            }

            addWelcomeMessage() {
                const welcomeMessage = this.chatMessages.querySelector('.message.welcome');
                if (!welcomeMessage) {
                    const messageDiv = document.createElement('div');
                    messageDiv.className = 'message assistant welcome';

                    const avatar = document.createElement('div');
                    avatar.className = 'message-avatar';
                    avatar.textContent = '🤖';

                    const messageContent = document.createElement('div');
                    messageContent.className = 'message-content';
                    messageContent.innerHTML = `
                        您好！我是天工开悟农业AI助手。我可以帮助您：<br>
                        • 识别作物病虫害<br>
                        • 提供防治建议<br>
                        • 解答农业相关问题<br>
                        • 分析农作物图片<br><br>
                        请开始对话吧！
                    `;

                    messageDiv.appendChild(avatar);
                    messageDiv.appendChild(messageContent);

                    const inputContainer = document.querySelector('.api-key-input');
                    this.chatMessages.insertBefore(messageDiv, inputContainer.nextSibling);
                }
            }

            generateSessionId() {
                return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            }

            formatTime(isoString) {
                const date = new Date(isoString);
                const now = new Date();
                const diffMs = now - date;
                const diffMins = Math.floor(diffMs / 60000);
                const diffHours = Math.floor(diffMs / 3600000);
                const diffDays = Math.floor(diffMs / 86400000);

                if (diffMins < 1) return '刚刚';
                if (diffMins < 60) return `${diffMins}分钟前`;
                if (diffHours < 24) return `${diffHours}小时前`;
                if (diffDays < 7) return `${diffDays}天前`;

                return date.toLocaleDateString('zh-CN', {
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            }

            loadChatSessions() {
                const saved = localStorage.getItem('kwoovaChats');
                if (saved) {
                    try {
                        this.chatSessions = JSON.parse(saved);
                    } catch (e) {
                        console.error('Failed to load chat sessions:', e);
                        this.chatSessions = [];
                    }
                }
            }

            saveChatSessions() {
                try {
                    localStorage.setItem('kwoovaChats', JSON.stringify(this.chatSessions));
                } catch (e) {
                    console.error('Failed to save chat sessions:', e);
                }
            }
        }

        // 全局变量，用于在HTML中调用方法
        let chatBot;

        // 初始化聊天机器人
        document.addEventListener('DOMContentLoaded', () => {
            chatBot = new AgricultureChatBot();
        });
    </script>
</body>
</html>